package es.andresimon.portfolio.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;

import es.andresimon.portfolio.domain.Picture;
import es.andresimon.portfolio.domain.ProjectPicture;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
import org.springframework.stereotype.Controller;

@RequestMapping("/projectpictures")
@Controller
public class ProjectPictureController {
	
	public static List<Picture> getPicturesByProjectId(Long projectId) {
		
		if (projectId == null) return null;
		
		List<Picture> pictureList = new ArrayList<Picture>();

		@SuppressWarnings("unchecked")
		List<ProjectPicture> projectPictureList = (List<ProjectPicture>) ProjectPicture.findProjectPicturesByProjectId(projectId).getResultList();
		if (projectPictureList != null) {
			for (ProjectPicture projectPicture : projectPictureList) {
				pictureList.add(PictureController.getPictureByPictureId(projectPicture.getPictureId()));
			}
		}
		return pictureList;	
	}
	

	@Autowired
    private GenericConversionService conversionService;

	@RequestMapping(method = RequestMethod.POST)
    public String create(@Valid ProjectPicture projectPicture, BindingResult result, Model model, HttpServletRequest request) {
        if (result.hasErrors()) {
            model.addAttribute("projectPicture", projectPicture);
            return "projectpictures/create";
        }
        projectPicture.persist();
        return "redirect:/projectpictures/" + encodeUrlPathSegment(projectPicture.getId().toString(), request);
    }

	@RequestMapping(params = "form", method = RequestMethod.GET)
    public String createForm(Model model) {
        model.addAttribute("projectPicture", new ProjectPicture());
        return "projectpictures/create";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, Model model) {
        model.addAttribute("projectpicture", ProjectPicture.findProjectPicture(id));
        model.addAttribute("itemId", id);
        return "projectpictures/show";
    }

	@RequestMapping(method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model model) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            model.addAttribute("projectpictures", ProjectPicture.findProjectPictureEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) ProjectPicture.countProjectPictures() / sizeNo;
            model.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            model.addAttribute("projectpictures", ProjectPicture.findAllProjectPictures());
        }
        return "projectpictures/list";
    }

	@RequestMapping(method = RequestMethod.PUT)
    public String update(@Valid ProjectPicture projectPicture, BindingResult result, Model model, HttpServletRequest request) {
        if (result.hasErrors()) {
            model.addAttribute("projectPicture", projectPicture);
            return "projectpictures/update";
        }
        projectPicture.merge();
        return "redirect:/projectpictures/" + encodeUrlPathSegment(projectPicture.getId().toString(), request);
    }

	@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("projectPicture", ProjectPicture.findProjectPicture(id));
        return "projectpictures/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model model) {
        ProjectPicture.findProjectPicture(id).remove();
        model.addAttribute("page", (page == null) ? "1" : page.toString());
        model.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/projectpictures?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());
    }

	@RequestMapping(params = { "find=ByProjectId", "form" }, method = RequestMethod.GET)
    public String findProjectPicturesByProjectIdForm(Model model) {
        return "projectpictures/findProjectPicturesByProjectId";
    }

	@RequestMapping(params = "find=ByProjectId", method = RequestMethod.GET)
    public String findProjectPicturesByProjectId(@RequestParam("projectId") Long projectId, Model model) {
        model.addAttribute("projectpictures", ProjectPicture.findProjectPicturesByProjectId(projectId).getResultList());
        return "projectpictures/list";
    }

	@RequestMapping(params = { "find=ByPictureId", "form" }, method = RequestMethod.GET)
    public String findProjectPicturesByPictureIdForm(Model model) {
        return "projectpictures/findProjectPicturesByPictureId";
    }

	@RequestMapping(params = "find=ByPictureId", method = RequestMethod.GET)
    public String findProjectPicturesByPictureId(@RequestParam("pictureId") Long pictureId, Model model) {
        model.addAttribute("projectpictures", ProjectPicture.findProjectPicturesByPictureId(pictureId).getResultList());
        return "projectpictures/list";
    }

	Converter<ProjectPicture, String> getProjectPictureConverter() {
        return new Converter<ProjectPicture, String>() {
            public String convert(ProjectPicture projectPicture) {
                return new StringBuilder().append(projectPicture.getProjectId()).append(" ").append(projectPicture.getPictureId()).append(" ").append(projectPicture.getWeight()).toString();
            }
        };
    }

	@PostConstruct
    void registerConverters() {
        conversionService.addConverter(getProjectPictureConverter());
    }

	private String encodeUrlPathSegment(String pathSegment, HttpServletRequest request) {
        String enc = request.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        }
        catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
